package pro.softzhang.algo.lc0;

import pro.softzhang.algo.flag.knowledge.KBinarySearch;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array
 */
public class LC34_FindFirstAndLastPositionOfElementInSortedArray {
    public static void main(String[] args) {

    }

    /**
     *
     */
    @KBinarySearch
    static
    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int start = findIdx(nums, target);
            if (start == nums.length || nums[start] != target) {
                return new int[]{-1, -1};
            }

            int end = findIdx(nums, target + 1) - 1;
            return new int[]{start, end};
        }

        /**
         * 开区间写法
         * @param nums
         * @param target
         * @return
         */
        private int findIdx(int[] nums, int target) {
            int left = -1, right = nums.length;
            while (left + 1 < right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] < target) {
                    left = mid;
                } else {
                    right = mid;
                }
            }
            return right;
        }
    }
}
